//
//  LoginViewController.m
//  KeleAppProject
//
//  Created by 周岑 on 2018/1/11.
//  Copyright © 2018年 Cen Zhou. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginHeader.h"
#import "LoginView.h"
#import "RegisterView.h"
#import "ThirdLoginView.h"
#import "LoginSegmentView.h"
#import "ForgetPwdVC.h"
#import "SendCodeButton.h"
@interface LoginViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) LoginView *loginView;
@property (nonatomic, strong) RegisterView *registerView;
@property (nonatomic, strong) ThirdLoginView *thirdLoginView;
@property (nonatomic, strong) LoginSegmentView *navTitleView;
@end

@implementation LoginViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configureLoginVc];
    [self loadLoginSubviews];
}

- (void)configureLoginVc{
    self.view.backgroundColor = [UIColor whiteColor];
    // 配置titleView
    self.navTitleView = [[LoginSegmentView alloc]initWithFrame:CGRectMake(0, 0, 114*WIDTH, 28)];
    self.navTitleView.delegateSignal = [RACSubject subject];
    self.navTitleView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.navTitleView;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"icon_fanhui" highImageName:@"icon_fanhui" target:self action:@selector(back)];
}

- (void)back{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

// loadUI
- (void)loadLoginSubviews{
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.thirdLoginView];
    [self addChildSubviewsOnScroll];
    [self loadConstrainsOnSubviews];
    [self addClicksOnLogin];
    
    
    
    // 注册
    self.registerView.delegateCode = [RACSubject subject];
    @weakify(self)
    [self.registerView.delegateCode subscribeNext:^(NSDictionary *x) {
        @strongify(self)
        NSString *phoneStr = x[@"phoneStr"];
        if (phoneStr.length<=0) {
            [SVProgressHUD showAlert:@"手机号不能为空"];
        }else if(![CheckMobile isPhoneNo:phoneStr]){
            [SVProgressHUD showAlert:@"请输入正确手机号"];
        }else{
            [self.registerView.codeButton initialTime];
            [[KeleData sharedInstance] sendPhoneCodeWithPhone:x[@"phoneStr"] success:^(id responseObject) {
                if ([responseObject[@"success"] integerValue] == 1) {
                    [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"error"] forKey:@"sessionId"];
                }
            } failure:^(NSError *error) {
                NSLog(@"login->sendcode->error->%@",error);
            }];
        }
        
    }];
    
    self.registerView.delegateSignal = [RACSubject subject];
    [self.registerView.delegateSignal subscribeNext:^(NSDictionary *x) {
        [SVProgressHUD showLoading:@"注册中..."];
        [[KeleData sharedInstance] registerWithPhone:x[@"phoneStr"] sessionId:SessionID code:x[@"codeStr"] password:x[@"pwd"] success:^(id responseObject) {
            
            [SVProgressHUD dismiss];
            if ([responseObject[@"success"] integerValue] == 1) {
                
                [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"id"] forKey:@"userId"];
                [self dismissViewControllerAnimated:YES completion:nil];
            }else{
                NSLog(@"login->register->error");
            }
            
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            NSLog(@"login->register->error->%@",error);
        }];
    }];
    
    
    // 登录  ------ 快速登录
    self.loginView.codeDelegate = [RACSubject subject];
    [self.loginView.codeDelegate subscribeNext:^(NSDictionary *x) {
        @strongify(self)
        NSString *phoneStr = x[@"phoneStr"];
        if (phoneStr.length<=0) {
            [SVProgressHUD showAlert:@"手机号不能为空"];
        }else if(![CheckMobile isPhoneNo:phoneStr]){
            [SVProgressHUD showAlert:@"请输入正确手机号"];
        }else{
            [self.loginView.sendCodeButton initialTime];
            [[KeleData sharedInstance] sendPhoneCodeWithPhone:x[@"phoneStr"] success:^(id responseObject) {
                
                if ([responseObject[@"success"] integerValue] == 1) {
                    [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"error"] forKey:@"sessionId"];
                    
                }
            } failure:^(NSError *error) {
                NSLog(@"login->sendcode->error->%@",error);
            }];
        }
        
    }];
    
    self.loginView.delegateSignal = [RACSubject subject];
    [self.loginView.delegateSignal subscribeNext:^(NSDictionary *x) {
        [SVProgressHUD showLoading:@"登录中..."];
        [[KeleData sharedInstance] phoneFastLoginWithPhone:x[@"phoneStr"] sessionId:SessionID code:x[@"codeStr"] success:^(id responseObject) {
            [SVProgressHUD dismiss];
            if ([responseObject[@"success"] integerValue] == 1) {
                [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"id"] forKey:@"userId"];
                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }else{
                NSLog(@"login->fast->isNotsuccess");
                [SVProgressHUD showError:responseObject[@"error"]];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            
            NSLog(@"login->fast->error->%@",error);
        }];
    }];
    
    // 登录  ----- 账号密码登录
    self.loginView.delegateAccount = [RACSubject subject];
    [self.loginView.delegateAccount subscribeNext:^(NSDictionary *x) {
        [SVProgressHUD showLoading:@"登录中..."];
        [[KeleData sharedInstance] phoneAccountLoginWithPhone:x[@"phoneStr"] password:x[@"pwd"] success:^(id responseObject) {
            [SVProgressHUD dismiss];
            if ([responseObject[@"success"] integerValue] == 1) {
                [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"id"] forKey:@"userId"];
                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }else{
                NSLog(@"login->fast->isNotsuccess");
                [SVProgressHUD showError:responseObject[@"error"]];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            
            NSLog(@"login->fast->error->%@",error);
        }];
    }];
    
    
    
    
}

// 加约束
- (void)loadConstrainsOnSubviews{
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(LGScrollH);
    }];
    [self.thirdLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}

// methords
- (void)addClicksOnLogin{
    [self.navTitleView.delegateSignal subscribeNext:^(NSDictionary *x) {
        [self.scrollView setContentOffset:CGPointMake(KLScreenW * [x[@"index"] integerValue], 0) animated:YES];
    }];
    self.loginView.delegateForget = [RACSubject subject];
    [self.loginView.delegateForget subscribeNext:^(id x) {
        ForgetPwdVC *forgetPwdVc = [[ForgetPwdVC alloc]init];
        [self.navigationController pushViewController:forgetPwdVc animated:YES];
    }];
}

// lazyload
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.bounces = YES;
        _scrollView.pagingEnabled = YES;
        _scrollView.contentSize = CGSizeMake(KLScreenW*2, 0);  // 禁止竖直滚动
        _scrollView.contentOffset = CGPointMake(0, 0);
    }
    return _scrollView;
}

- (LoginView *)loginView{
    if (!_loginView) {
        _loginView = [[LoginView alloc]initWithFrame:CGRectMake(KLScreenW, 0, KLScreenW, LGScrollH)];
        _loginView.backgroundColor = [UIColor whiteColor];
        // 是否是账号密码登录的
        if ([_loginView.loginBtn.titleLabel.text isEqualToString:PhoneLogin]) {
            _loginView.delegateSignal = [RACSubject subject];
        }
    }
    return _loginView;
    
}

- (RegisterView *)registerView{
    if (!_registerView) {
        _registerView = [[RegisterView alloc]initWithFrame:CGRectMake(0, 0, KLScreenW, LGScrollH)];
        _registerView.backgroundColor = [UIColor whiteColor];
    }
    return _registerView;
}

- (ThirdLoginView *)thirdLoginView{
    if (!_thirdLoginView) {
        _thirdLoginView = [[ThirdLoginView alloc]init];
        _thirdLoginView.backgroundColor = [UIColor whiteColor];
    }
    return _thirdLoginView;
}

// 将滑动的登录注册添加进来
- (void)addChildSubviewsOnScroll{
    [self.scrollView addSubview:self.registerView];
    [self.scrollView addSubview:self.loginView];
}


#pragma mark --- scrollview的代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/KLScreenW;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNavIndex" object:@{@"index":@(index)}];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc{
    NSLog(@"LoginViewController 销毁");
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
